package com.itheima.controller;


import com.github.pagehelper.Page;
import com.itheima.dto.MessageConstant;
import com.itheima.dto.PageResult;
import com.itheima.dto.QueryPageBean;
import com.itheima.dto.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import com.itheima.utils.DateUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/member")
public class MemberController {

    @Autowired
    private MemberService memberService;


    //根据id查询员工
    @GetMapping("/{id}")
    public Result selectById(@PathVariable Integer id) {
        Member member = memberService.findById (id);
        return Result.success (member, "查询员工数据成功");
    }

    //编辑员工-
    @PutMapping
    public Result updateById(@RequestBody Member member) {
        memberService.updateById (member);
        return Result.success ("修改数据成功");
    }

    //导出会员
    @GetMapping("/exportExcel")
    public Result exportExcel(@RequestParam("ids") List<Integer> ids, HttpServletResponse response) {

        //取出返回结果数据，准备将报表数据写入到Excel文件中


        try {
//            XSSFWorkbook excel = new XSSFWorkbook (new FileInputStream ("/root/static/template/member.xlsx"));

            //创建一个excel文档
            XSSFWorkbook excel = new XSSFWorkbook ( );
            //创建一个 sheet页
            XSSFSheet sheet = excel.createSheet ("会员数据");

            //表头
            XSSFRow firstRow = sheet.createRow (0);
            firstRow.createCell (0).setCellValue ("档案号");
            firstRow.createCell (1).setCellValue ("姓名");
            firstRow.createCell (2).setCellValue ("性别");
            firstRow.createCell (3).setCellValue ("年龄");
            firstRow.createCell (4).setCellValue ("健康管理师");
            firstRow.createCell (5).setCellValue ("注册时间");
            firstRow.createCell (6).setCellValue ("手机号码");
            firstRow.createCell (7).setCellValue ("套餐");
            //表头下面数据
            List<Member> members = new ArrayList<> ( );
            for (Integer id : ids) {
                Member member = memberService.findById (id);
                members.add (member);
            }
            int countRow = 1;
            for (Member member : members) {
                XSSFRow row = sheet.createRow (countRow);
                String fileNumber = member.getFileNumber ( );//档案号
                String name = member.getName ( );//姓名
                String sex = member.getSex ( );//性别
                sex = ("1".equals (sex)) ? "男" : "女";
                DateUtils.dateDiff (member);
                String age = member.getAge ( ).toString ( );
                Date regTime = member.getRegTime ( );
                String date = DateUtils.parseDate2String (regTime);
                String manager = member.getManager ( );
                String phoneNumber = member.getPhoneNumber ( );
                row.createCell (0).setCellValue (fileNumber.isEmpty ( ) ? "" : fileNumber);
                row.createCell (1).setCellValue (name.isEmpty ( ) ? "" : name);
                row.createCell (2).setCellValue (sex);
                row.createCell (3).setCellValue (age.isEmpty ( ) ? "" : age);
                row.createCell (4).setCellValue (manager.isEmpty ( ) ? "" : manager);
                row.createCell (5).setCellValue (date.isEmpty ( ) ? "" : date);
                row.createCell (6).setCellValue (phoneNumber.isEmpty ( ) ? "" : phoneNumber);
                Integer memberId = member.getId ( );
                List<String> names = memberService.findNames (memberId);
                String setMeal = names.isEmpty ( ) ? "" : names.get (0);
                String substring = setMeal.substring (1, setMeal.length ( ) - 1);
                row.createCell (7).setCellValue (substring);
                countRow++;
            }
            //使用输出流进行表格下载,基于浏览器作为客户端下载
            OutputStream out = response.getOutputStream ( );
            response.setContentType ("application/vnd.ms-excel");//代表的是Excel文件类型 content-type  application/vnd.ms-excel
            // response.setHeader("Content-Type","application/vnd.ms-excel");
            response.setHeader ("content-Disposition", "attachment;filename=member.xlsx");//指定以附件形式进行下载 强制下载！！

            //excel
            excel.write (out);

            out.flush ( );
            out.close ( );
            excel.close ( );
            return null;
        } catch (Exception e) {
            return Result.error (MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
        }
    }


    //分页查询
    /*Integer currentPage;页码
    Integer pageSize;每页记录数
    String queryString;查询条件*/
    @PostMapping("/findPage")
    public PageResult page(@RequestBody QueryPageBean queryPageBean) {

        System.out.println ("分页查询方法开始执行");

        PageResult page = memberService.findPage (queryPageBean);

        return page;

    }


    //新增会员
    @PostMapping
    public Result add(@RequestBody Member member) {

        memberService.add (member);
        return Result.success ("新增成功");


        /*//获取
        Member member2 = (Member) request.getSession().getAttribute("member");
        //请求数据没有密码,设置默认密码123456,并用md5加密
        member.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        //获取当前系统时间
        LocalDateTime now = LocalDateTime.now();*/
    }

    //删除会员
    @DeleteMapping("/{id}")
    public Result deleteMember(@PathVariable Integer id) {
        memberService.deleteById (id);
        return Result.success ("删除成功");
    }


}
